package com.design.testdemo.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import com.design.testdemo.R;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;

public class InfoActivity extends AppCompatActivity implements Runnable {

    @BindView(R.id.tv_time)
    TextView mTvTime;
    private long time;

    private Handler mHandler = new Handler();
    private long startTime;
    private Date mDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);
        ButterKnife.bind(this);

        mDate = new Date();

        startTime = new Date().getTime() - time;

        mHandler.post(this);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    /**
     * 得到一个格式化的时间
     *
     * @param time 时间 毫秒
     * @return 分：秒：毫秒
     */
    private String getFormatTime(long time) {

        long millisecond = time % 1000;
        long second = (time / 1000) % 60;
        long minute = time / 1000 / 60;

        //秒以下的只显示一位
        String strMillisecond = millisecond / 10 + "";

        if (strMillisecond.length() == 1) {
            strMillisecond = "0" + strMillisecond;
        }

        //秒显示两位
        String strSecond = ("00" + second).substring(("00" + second).length() - 2);
        //分显示两位
        String strMinute = ("00" + minute).substring(("00" + minute).length() - 2);

        return strMinute + ":" + strSecond + "." + strMillisecond;
    }

    @Override
    public void run() {
        mHandler.postDelayed(this, 50);
        time = new Date().getTime() - startTime;
        mTvTime.setText(getFormatTime(time));
    }
}
